﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows.Documents;
using System.Windows.Threading;

namespace PersonaLibrary.ViewModel.PrintViewModel
{
	public abstract class BasePrintTemplate : INotifyPropertyChanged, IBasePrintTemplate
	{
		public List<Data.Employee> Items { get; set; }
		public string TemplateName { set; get; }

		public bool IsBusy { private set; get; }
		public IDocumentPaginatorSource Document { private set; get; }

		private Size _lastPageSize;
		private Thickness _lastThickness;

		protected List<UserControl> CoveredItems;

		private Stopwatch _timer;

		#region Methods

		public void Refresh()
		{
			Refresh(_lastPageSize, _lastThickness);
		}

		public void Refresh(Size pageSize, Thickness thickness)
		{
			IsBusy = true;
			RisePropertyChanged("IsBusy");
			_timer = Stopwatch.StartNew();

			_lastPageSize = pageSize;
			_lastThickness = thickness;

			Func<Size, Thickness, IDocumentPaginatorSource> func = CreateTable;
			DispatcherOperation operation = ((App)Application.Current).Dispatcher.BeginInvoke(func,
																							   DispatcherPriority.Background,
																							   new object[]
			                                                                                    {
			                                                                                        pageSize, thickness
			                                                                                    }
				);
			operation.Completed += OperationCompleted;
		}

		void OperationCompleted(object sender, EventArgs e)
		{
			IsBusy = false;
			RisePropertyChanged("IsBusy");

			Document = ((DispatcherOperation)sender).Result as IDocumentPaginatorSource;
			RisePropertyChanged("Document");

			_timer.Stop();
			Debug.WriteLine("Refresh time " + _timer.Elapsed);
		}

		protected abstract IDocumentPaginatorSource CreateTable(Size pageSize, Thickness thickness);
		
		protected void RisePropertyChanged(string name)
		{
			PropertyChanged(this, new PropertyChangedEventArgs(name));
		}

		public abstract void UnLoad();

		#endregion

		#region Events

		public event PropertyChangedEventHandler PropertyChanged = delegate { };

		#endregion
	}
}
